package com.java1234.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;

@Component
public class DecryptUtil {

    private static final String ALGORITHM = "RSA";
    private static final String TRANSFORMATION = "RSA/ECB/PKCS1Padding";

    // 私钥 (应从更安全的地方加载)
    private static final String PRIVATE_KEY = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqhHyZfSsYourNxaY\n" +
            "7Nt+PrgrxkiA50efORdI5U5lsW79MmFnusUA355oaSXcLhu5xxB38SMSyP2KvuKN\n" +
            "PuH3owIDAQABAkAfoiLyL+Z4lf4Myxk6xUDgLaWGximj20CUf+5BKKnlrK+Ed8gA\n" +
            "kM0HqoTt2UZwA5E2MzS4EI2gjfQhz5X28uqxAiEA3wNFxfrCZlSZHb0gn2zDpWow\n" +
            "cSxQAgiCstxGUoOqlW8CIQDDOerGKH5OmCJ4Z21v+F25WaHYPxCFMvwxpcw99Ecv\n" +
            "DQIgIdhDTIqD2jfYjPTY8Jj3EDGPbH2HHuffvflECt3Ek60CIQCFRlCkHpi7hthh\n" +
            "YhovyloRYsM+IS9h/0BzlEAuO0ktMQIgSPT3aFAgJYwKpqRYKlLDVcflZFCKY7u3\n" +
            "UP8iWi1Qw0Y=";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 解密方法
     *
     * @param encryptedData Base64编码后的加密数据
     * @return 解密后的字符串
     * @throws Exception 如果解密失败，则抛出异常
     */
    public String decrypt(String encryptedData) throws Exception {
        byte[] decodedEncryptedData = Base64.decode(encryptedData.getBytes("UTF-8"));
        PrivateKey privateKey = getPrivateKey();
        Cipher cipher = Cipher.getInstance(TRANSFORMATION, "BC");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(decodedEncryptedData);
        return new String(decryptedBytes, "UTF-8");
    }

    /**
     * 获取私钥对象
     *
     * @return 私钥对象
     * @throws Exception 如果生成私钥失败，则抛出异常
     */
    private PrivateKey getPrivateKey() throws Exception {
        byte[] keyBytes = Base64.decode(PRIVATE_KEY.getBytes("UTF-8"));
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, "BC");
        return keyFactory.generatePrivate(spec);
    }

    /**
     * 测试方法（可选）
     */
    public static void main(String[] args) {
        try {
            DecryptUtil decryptUtil = new DecryptUtil();

            // 示例加密数据，需要替换为真实的加密数据
            String encryptedData = "your-base64-encoded-encrypted-data-here";

            // 解密并打印结果
            System.out.println("Decrypted data: " + decryptUtil.decrypt(encryptedData));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}